package com.clearinghouse.service;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.clearinghouse.entity.Account;

/**
 * Session Bean implementation class ClearingHouseBean
 * 
 * Based on: http://programming.manessinger.com/tutorials/an-eclipse-glassfish-java-ee-6-tutorial/
 */
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
@LocalBean
@WebService
public class ClearingHouseBean implements ClearingHouseBeanRemote {
	
	@PersistenceContext(unitName = "ClearingHouseEJB")
    private EntityManager em1;

    /**
     * Default constructor. 
     */
    public ClearingHouseBean() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public double getSaldo(int rekeningnummer) {
		return getAccountByRekeningnummer(rekeningnummer).getSaldo();
	}
	
	private Account getAccountByRekeningnummer(int rekeningnummer) {
		TypedQuery<Account> query = em1.createNamedQuery("Account.findByRekeningnummer", Account.class);
		query.setParameter("arekeningnummer", rekeningnummer);
		List<Account> result = query.getResultList();
		
		if(result.size() == 1){
        	// Rekeningnummer has unique index. If size is 1, then found, else not found
        	return result.get(0);
        }else{
        	return null;
        }
	}
}
